

import 'dart:io';

import 'package:baidu_map/utils/log_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';

class SingleLocationWithoutMapPage extends StatefulWidget {
  const SingleLocationWithoutMapPage({super.key});

  @override
  State<SingleLocationWithoutMapPage> createState() => _SingleLocationWithoutMapPageState();
}

class _SingleLocationWithoutMapPageState extends State<SingleLocationWithoutMapPage> {
  BaiduLocation _locationResult = BaiduLocation();
  final LocationFlutterPlugin _myLocPlugin = LocationFlutterPlugin();
  bool _suc = false;

  @override
  void initState() {
    super.initState();
    if (Platform.isIOS) {
      _myLocPlugin.singleLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _locationResult = result;
        });
      });
    } else if (Platform.isAndroid) {
      _myLocPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
        setState(() {
          _locationResult = result;
          _myLocPlugin.stopLocation();
        });
      });
    }
  }

  void _locationAction() async {
    Map iosMap = BaiduLocationIOSOption(
        coordType: BMFLocationCoordType.bd09ll,
        BMKLocationCoordinateType: 'BMKLocationCoordinateTypeBMK09LL',
        desiredAccuracy: BMFDesiredAccuracy.best
      ).getMap();

    Map androidMap = BaiduLocationAndroidOption(
        coordType: BMFLocationCoordType.bd09ll,
        locationMode: BMFLocationMode.hightAccuracy,
        isNeedAddress: true,
        isNeedAltitude: true,
        isNeedLocationDescribe: true,
        isNeedNewVersionRgc: true,
        isNeedLocationPoiList: true,
        openGps: true,
        locationPurpose: BMFLocationPurpose.sport,
      ).getMap();

    _suc = await _myLocPlugin.prepareLoc(androidMap, iosMap);
  }

  Future<void> _startLocation() async{
    if (Platform.isIOS) {
      _suc = await _myLocPlugin
            .singleLocation({'isReGeocode': true, 'isNetworkState': true});
    } else if (Platform.isAndroid) {
      _suc = await _myLocPlugin.startLocation();
    }
    LogUtil.i('开始单次定位：$_suc');
  }

  final GlobalKey _buttonKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    List<Widget> resultWidgets = [];
    if (_locationResult.locTime != null) {
      _locationResult.getMap().forEach((key, value) {
        resultWidgets.add(_resultWidget(key, value));
      });
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('单次定位(无地图)'),
      ),
      // appBar: BMFAppBar(
      //   title: '单次定位(无地图)',
      //   isBack: true,
      //   onBack: () {
      //     Navigator.pop(context);
      //   },
      // ),
      body: Column(
        children: [
          Container(
            color: Colors.blue[100],
            child: SizedBox(
              height: MediaQuery.of(context).size.height - 81 - 48,
              child: ListView(
                children: resultWidgets,
              ),
            ),
          ),
          ElevatedButton(
            key: _buttonKey,
            onPressed: () {
              ///设置定位参数
              _locationAction();
              _startLocation();

              LogUtil.d('ElevatedButton的高度是${_buttonKey.currentContext?.size}');
            },
            child: const Text('开始定位')
          )
        ],
      ),
    );
  }

  Widget _resultWidget(key, value) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('$key: ' '$value')
        ],
      ),
    );
  }
}